<?php

declare(strict_types=1);

namespace app\admin\model;

use app\admin\model\LogisticsCompany;
use think\facade\Db;
use think\Model;

class LogisticsRules extends Model
{





    // 定义数据表名
    protected $name = 'logistics_rules';

    // 定义主键
    protected $primaryKey = 'id';

    // 定义创建时间字段名
    protected $createTime = 'create_time';

    // 定义更新时间字段名
    protected $updateTime = 'update_time';
    // 定义自动时间戳
    protected $autoWriteTimestamp = true;


    // 定义一个通用的访问器来获取属性值
    protected $attributes = [

        'warehouse' => [],
        'terms' => [
            1 => 'DDP',
            2 => 'DDU'
        ],
        'status' => [
            0 => '关闭',
            1 => '开启'
        ],
        'prescription' => [
            1 => '普快',
            2 => '特快'
        ]
    ];

    public function __construct($data = [])
    {
        parent::__construct($data);
    }


    public function getAttr($name)
    {
        // 检查是否是要处理的特殊属性
        if (strpos($name, '_value') !== false) {
            $originalField = str_replace('_value', '', $name);
            if (isset($this->attributes[$originalField])) {
                $value = $this->getData($originalField);
                return $this->attributes[$originalField][$value] ?? '未知';
            }
        }

        // 如果不是特殊属性，调用父类的方法
        return parent::getAttr($name);
    }

    public function getFieldEnum($field)
    {

        if ('ALL' === strtoupper($field)) {
            $regionCountry = new RegionCountry;
            $warehouseModel = new Warehouse;
            $oInventory = new Inventory;
            return [
                'to_nation' => $regionCountry->getSelectOption([], "id,concat (cname,' (',full_name,') ') as name,country_code"),
//                'warehouse' => $warehouseModel->getSelectOption(['status' => 1, 'is_del' => 0]),
                'warehouse' => $oInventory->getWarehouseParentTreeEnum(),
                'terms' => $this->attributes['terms'],
                'status' => $this->attributes['status'],
                'prescription' => $this->attributes['prescription'],
            ];
        } else {
            switch ($field) {
                case 'to_nation':
                    $regionCountry = new RegionCountry;
                    return ['to_nation' => $regionCountry->getSelectOption([], "id,concat (cname,' (',full_name,') ') as name,country_code")];
                case 'warehouse':
                    $warehouseModel = new Warehouse;
                    return ['to_nation' =>  $warehouseModel->getSelectOption(['status' => 1, 'is_del' => 0])];
                    break;
                default:
                    return [$field => $this->$field];
            }
        }
    }





    public function creatorName()
    {
        return $this->hasOne('Operator', 'id', 'creator');
    }

    public function updaterName()
    {
        return $this->hasOne('Operator', 'id', 'updater');
    }


    public function logisticsCompanyObject()
    {
        return $this->hasOne('LogisticsCompany', 'id', 'logistics_company');
    }

    public function shippingWarehouseName()
    {
        return $this->hasOne('Warehouse', 'id', 'shipping_warehouse');
    }


    public function toNationName()
    {
        return $this->hasOne('region_country', 'id', 'to_nation');
    }


    /**
     *  批量修改
     */
    public static function updateAll($data)
    {

        $tableName = 'db_logistics_rules';
        $primaryKey = 'id';
        $updates = [];
        $sql = '';
        /* 批量写入暂时取消 */
        //        foreach ($data as $item) {
        //            $updates[0] = "UPDATE $tableName SET ";
        //            $updateFields = [];
        //            foreach ($item as $key => $value) {
        //                if ($key != $primaryKey) {
        //                    $updateFields[] = "`{$key}` = '$value'";
        //                }
        //            }
        //            $updates[1] = implode(', ', $updateFields);
        //            $updates[2] = "WHERE `{$primaryKey}` = '{$item[$primaryKey]}'";
        //            $sql.= implode('', $updates);
        //        }
        //
        //        return Db::execute($sql);

        /* 逐条写入 */
        foreach ($data as $item) {
            self::update($item);
        }
    }
}
